package com.zf.shuashua.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.chad.library.adapter.base.BaseViewHolder;
import com.lxj.xpopup.XPopup;
import com.meis.base.mei.adapter.BaseMultiAdapter;
import com.meis.base.mei.utils.NumberUtils;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.ToggleLikeBean;
import com.zf.shuashua.bean.comment.UserEntity;
import com.zf.shuashua.bean.home.HotVideoEntity;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.home.ShareVideoPopup;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.widget.SampleCoverVideo;

import java.util.ArrayList;
import java.util.Random;

public class HotVideoMultiAdapter extends BaseMultiAdapter<HotVideoEntity> {

    public static final String TAG = "HotVideoMultiAdapter";

    FragmentActivity context;
    ImageView imageView;
    GSYVideoOptionBuilder gsyVideoOptionBuilder;

    private OnItemClickListener clickListener;

    public static final int HOT_VIDEO_STYLE = 0;
    public static final int AD_STYLE = 1;

    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     * <p>
     * data A new list is created out of this one to avoid mutable list
     */
    public HotVideoMultiAdapter(FragmentActivity context, OnItemClickListener listener) {
        super(new ArrayList<>());
        addItemType(HOT_VIDEO_STYLE, R.layout.item_hot_video2);
        addItemType(AD_STYLE, R.layout.item_ad_hot_video);

        this.clickListener = listener;
        this.context = context;
        imageView = new ImageView(context);
        gsyVideoOptionBuilder = new GSYVideoOptionBuilder();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, HotVideoEntity item) {
        super.convert(helper, item);

        helper.itemView.setTag(helper.getAdapterPosition() + "");
        if (item.itemType == 0) {
            String url = getNonText(item.media_url);
            String title = getNonText(item.description);

            if (item.user == null) {
                item.user = new UserEntity();
            }

            SampleCoverVideo gsyVideoPlayer = helper.getView(R.id.video_layout);
            // CommonUtil
            TextView tvTime = helper.getView(R.id.tv_time);
            tvTime.setText(CommonUtil.stringForTime(item.length * 1000));

            gsyVideoPlayer.setOnBottomControlVisibilityListener(isVisible -> tvTime.setVisibility(isVisible ? View.GONE : View.VISIBLE));

            gsyVideoOptionBuilder
                    .setIsTouchWiget(false)
                    //.setThumbImageView(imageView)
                    .setUrl(url)
                    .setVideoTitle(title)
                    .setCacheWithPlay(false)
                    .setRotateViewAuto(true)
                    .setLockLand(true)
                    .setPlayTag(TAG)
                    .setShowFullAnimation(true)
                    .setNeedLockFull(true)
                    .setPlayPosition(helper.getAdapterPosition())
                    .setVideoAllCallBack(new GSYSampleCallBack() {
                        @Override
                        public void onPrepared(String url, Object... objects) {
                            super.onPrepared(url, objects);
                            if (!gsyVideoPlayer.isIfCurrentIsFullscreen()) {
                                // 静音
                                // GSYVideoManager.instance().setNeedMute(true);
                            }
                            if(!Store.getInstance().isLogin()){
                                return;
                            }
                            HttpData.getInstance().reportHotWatch(item.id, 12, 15, new ACallback<BaseData>() {
                                @Override
                                public void onSuccess(BaseData data) {

                                }

                                @Override
                                public void onFail(int errCode, String errMsg) {
                                }
                            });
                        }

                        @Override
                        public void onClickStartIcon(String url, Object... objects) {

                        }

                        @Override
                        public void onQuitFullscreen(String url, Object... objects) {
                            super.onQuitFullscreen(url, objects);
                            //全屏不静音
                            //GSYVideoManager.instance().setNeedMute(true);
                        }

                        @Override
                        public void onEnterFullscreen(String url, Object... objects) {
                            super.onEnterFullscreen(url, objects);
                            GSYVideoManager.instance().setNeedMute(false);
                            gsyVideoPlayer.getCurrentPlayer().getTitleTextView().setText((String) objects[0]);
                        }
                    }).build(gsyVideoPlayer);

            //增加title
            gsyVideoPlayer.getTitleTextView().setVisibility(View.GONE);

            //设置返回键
            gsyVideoPlayer.getBackButton().setVisibility(View.GONE);

            //设置全屏按键功能
            gsyVideoPlayer.getFullscreenButton().setOnClickListener(v -> resolveFullBtn(gsyVideoPlayer));

            gsyVideoPlayer.loadCoverImage(getNonText(item.avatar), Color.parseColor("#000000"));

            helper.setText(R.id.tv_title, title);

            ImageView ivAvatar = helper.getView(R.id.iv_avatar);
//            Glide.with(mContext)
//                    .load(item.user.avatar + "")
//                    .circleCrop()
//                    .into(ivAvatar);

            // item.user.name
            helper.setText(R.id.tv_name, NumberUtils.INSTANCE.convertOneDecimalW(new Random().nextBoolean() ? (12000 + new Random().nextInt(3000)) :
                    (4000 + new Random().nextInt(4000))) + "  次播放")
                    .setText(R.id.tv_praise_num, NumberUtils.INSTANCE.convertOneDecimalW(item.praise_count))
                    .setText(R.id.tv_comment_num, NumberUtils.INSTANCE.convertOneDecimalW(item.comment_count));
            ImageView ivPraise = helper.getView(R.id.iv_praise);
            ivPraise.setImageResource(item.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);

            helper.getView(R.id.praise_layout).setOnClickListener(v -> {
                if (!Store.getInstance().isLogin()) {
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    v.setEnabled(false);
                    boolean isPraise = item.is_praise_user;
                    isPraise = !isPraise;
                    int praiseCount = item.praise_count;
                    if (isPraise) {
                        item.praise_count = praiseCount + 1;
                    } else {
                        item.praise_count = (praiseCount - 1) < 0 ? 0 : (praiseCount - 1);
                    }
                    item.is_praise_user = isPraise;
                    helper.setText(R.id.tv_praise_num, NumberUtils.INSTANCE.convertOneDecimalW(item.praise_count));
                    ivPraise.setImageResource(item.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);

                    final boolean isFinalPraise = isPraise;
                    reportAdvertAction(TrackConstants.ACTION_HOME_LIKE, TrackConstants.NOTE_HOME_LIKE);
                    HttpData.getInstance().toToggleLike(item.id, new AbsCallback<BaseData<ToggleLikeBean>>() {
                        @Override
                        public void onRealSuccess(BaseData<ToggleLikeBean> data2) {
                            if (data2 == null || data2.getData() == null) {
                                ToastUtil.showToast(mContext, "系统错误");
                                return;
                            }
                            v.setEnabled(true);
                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            int praiseCount = item.praise_count;
                            if (!isFinalPraise) {
                                item.praise_count = praiseCount + 1;
                            } else {
                                item.praise_count = (praiseCount - 1) < 0 ? 0 : (praiseCount - 1);
                            }
                            item.is_praise_user = !isFinalPraise;
                            helper.setText(R.id.tv_praise_num, NumberUtils.INSTANCE.convertOneDecimalW(item.praise_count));
                            ivPraise.setImageResource(item.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);
                            v.setEnabled(true);
                        }
                    });
                }
            });

            ivAvatar.setOnClickListener(v -> {
                if (clickListener != null) {
                    // clickListener.onJumpUserDetail(item.user_id, helper.getAdapterPosition());

                    //分享
                    if (!Store.getInstance().isLogin()) {
                        mContext.startActivity(new Intent(mContext, LoginActivity.class));
                    } else {
                        reportAdvertAction(TrackConstants.ACTION_HOME_SHARE, TrackConstants.NOTE_HOME_SHARE);
                        Store.getInstance().setVideoId(String.valueOf(item.id));
                        new XPopup.Builder(context)
                                .hasShadowBg(false) // 去掉半透明背景
                                .asCustom(new ShareVideoPopup(context, item.description, item.description, item.id + ""))
                                .show();
                    }
                }
            });

            helper.itemView.setOnClickListener(v -> {
                v.setEnabled(false);
                if (clickListener != null) {
                    item.is_video_paused = gsyVideoPlayer.getCurrentState() != GSYVideoView.CURRENT_STATE_PLAYING;
                    item.currentPosition = gsyVideoPlayer.getCurrentPositionWhenPlaying();
                    clickListener.onJumpDetail(gsyVideoPlayer, gsyVideoPlayer.getGSYVideoManager(), item, helper.getAdapterPosition());
                }
                v.postDelayed(() -> v.setEnabled(true), 800);
            });

//            helper.setVisible(R.id.tv_follow, item.follow_status == 0);
//            helper.getView(R.id.tv_follow).setOnClickListener(v -> {
//                if (!Store.getInstance().isLogin()) {
//                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
//                }
//                if (clickListener != null) {
//                    clickListener.onFollow(item.user_id, helper.getAdapterPosition());
//                }
//            });

        } else if (item.itemType == 1) {
//            final NativeExpressADView adView = item.nativeExpressADView;
            final View adView = item.view;
            FrameLayout advertLayout = helper.getView(R.id.advert_container);
            if (advertLayout.getChildCount() > 0) {
                advertLayout.removeAllViews();
            }

            if (adView.getParent() != null) {
                ((ViewGroup) adView.getParent()).removeView(adView);
            }

            advertLayout.addView(adView);

            helper.setText(R.id.tv_praise_num, NumberUtils.INSTANCE.convertOneDecimalW(item.praise_count))
                    .setText(R.id.tv_name, NumberUtils.INSTANCE.convertOneDecimalW(new Random().nextBoolean() ? (12000 + new Random().nextInt(3000)) :
                            (4000 + new Random().nextInt(4000))) + "  次播放")
                    .setText(R.id.tv_comment_num, NumberUtils.INSTANCE.convertOneDecimalW(item.comment_count));
            ImageView ivPraise = helper.getView(R.id.iv_praise);
            ivPraise.setImageResource(item.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);
            helper.getView(R.id.praise_layout).setOnClickListener(v -> {
                item.is_praise_user = !item.is_praise_user;
                ivPraise.setImageResource(item.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);

                if (item.is_praise_user) {
                    item.praise_count += 1;
                } else {
                    item.praise_count -= 1;
                }
                helper.setText(R.id.tv_praise_num, NumberUtils.INSTANCE.convertOneDecimalW(item.praise_count));
            });

            // 调用render方法后sdk才会开始展示广告
            //  adView.render();
        }

    }

    public interface OnItemClickListener {
        void onJumpDetail(SampleCoverVideo videoView, GSYVideoViewBridge viewBridge, HotVideoEntity entity, int position);

        void onFollow(int userId, int position);

        void onJumpUserDetail(int userId, int position);
    }

    private String getNonText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    /**
     * 全屏幕按键处理
     */
    private void resolveFullBtn(final StandardGSYVideoPlayer standardGSYVideoPlayer) {
        standardGSYVideoPlayer.startWindowFullscreen(context, true, true);
    }

    private void reportAdvertAction(String action, String note) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_HOME, action, note);
    }
}
